import random
import re

import redis
import requests


def random_mobile_code(length=6):
    return ''.join(random.choices('0123456789', k=length))


def send_message_by_sms(*, tel, message):
    resp = requests.post(
        url='http://sms-api.luosimao.com/v1/send.json',
        auth=('api', 'key-850e8bf271c17d1e0fe12a7754807f32'),
        data={
            'mobile': tel,
            'message': message
        }, timeout=3, verify=False)
    return resp.json()


client = redis.Redis(host='47.104.31.138', port=5489, password='Luohao.618')
pattern = re.compile(r'1[3-9]\d{9}')
tel = input('请输入你的手机号: ')
if pattern.fullmatch(tel):
    if client.get(f'example08:{tel}'):
        print('请不要在120秒内重复发送短信验证码')
    else:
        total = client.get(f'example08:total:{tel}')
        total = int(total) if total else 0
        if total < 3:
            code = random_mobile_code()
            result = send_message_by_sms(
                tel=tel,
                message=f'您的短信验证码是{code}，打死也不能告诉别人。【Python小课】'
            )
            if result['error'] == 0:
                client.set(f'example08:{tel}', code, ex=120)
                print('短信验证码已经发送到您的手机')
                if total == 0:
                    client.set(f'example08:total:{tel}', 1, ex=86400)
                else:
                    client.incr(f'example08:total:{tel}')
        else:
            print('24小时以内不能再发送短信验证码！！！')
else:
    print('无效的手机号码！！！')
